<?php

/**
 * Created by PhpStorm.
 * User: xhkj
 * Date: 2018/8/10
 * Time: 下午1:54
 */

namespace globalunit\utils;

use QYS\Locker\RedLock;
use QYS\Core\Config as QYSConfig;

class MyMysqlLocker
{
    public  static $servers = null;

    private $lock_id = null;
    private $redLock = null;

    private $is_autocommit = false;
    private $mysql = null;

    public function __construct($rediscli, $mysql, $key, $sec, $count = 3)
    {
        $redLock = new RedLock($rediscli);
        $this->redLock = $redLock;

        $lock_id = $redLock->lock($key, $sec);
        $this->lock_id = $lock_id;

        $this->mysql = $mysql;
        $this->mysql->autocommit(false);
    }

    public function islocked()
    {
        return $this->lock_id;
    }

    public function getautocommit()
    {
        return $this->is_autocommit;
    }

    public function autocommit($mode)
    {
        $this->is_autocommit = $mode;
    }

    public  function  __destruct()
    {
        if ($this->is_autocommit === false) {
            $this->mysql->rollback();
        } else {
            $this->mysql->commit();
        }

        $this->mysql->autocommit(true);

        if ($this->lock_id) {
            $this->redLock->unlock($this->lock_id);
        }
    }
}
